package com.linktrip.devicemanager.sms;

import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.linktrip.devicemanager.util.Constant;
import com.linktrip.devicemanager.util.HttpUtil;
import com.linktrip.devicemanager.util.ToolKits;

/**
 * @author : CaineZhu E-mail:CaineZhu@me.com
 * @version : V1.0
 * @创建时间 : 2017年3月31日 上午9:55:42
 * @类说明 : token 管理类
 */
public class SMSUtil {

	static Logger logger = LoggerFactory.getLogger(SMSUtil.class);

	// 短信token 2小时有效期 最多12次/小时
	public static String TOKEN_SMS = "";

	public static void getToken() throws UnsupportedEncodingException {

		String url = SMSConfig.getIOTTokenUrl();
		String params = "username=" + SMSConfig.getIOTUserName() + "&password=" + SMSConfig.getIOTPassWord();
		JSONObject obj = JSONObject.parseObject(HttpUtil.httpUrlConnection(url, Constant.DEFAULT_POST, params));
		int code = obj.getIntValue("code");
		if (code == 200) {
			SMSUtil.TOKEN_SMS = obj.getString("token");
			logger.debug("getToken()=>token:{}", SMSUtil.TOKEN_SMS);
		} else {
			logger.error("getToken()=>msg:{} code:{}", new String(obj.getString("msg").getBytes(), "utf-8"), code);
		}
	}

	public static boolean send(String content, String... ids) {
		if (ToolKits.isEmpty(SMSUtil.TOKEN_SMS))
			try {
				getToken();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		if (ToolKits.isEmpty(SMSUtil.TOKEN_SMS)) {
			logger.info("send()=>result:get token error! return false.");
			return false;
		}
		String token = "JWT " + SMSUtil.TOKEN_SMS;
		String url = SMSConfig.getIOTSendSMSUrl();
		SendRquest req = new SendRquest(ids, content);
		String params = JSONObject.toJSON(req).toString();
		String result = HttpUtil.httpUrlConnectionForJson(url, Constant.DEFAULT_POST, params, token);
		logger.info("send()=>result:{}", result);
		JSONObject obj = JSONObject.parseObject(result);

		int code = obj.getIntValue("code");
		Object[] fails = obj.getJSONArray("failed").toArray();
		logger.info("code:{} fails:{}",code,fails.length);
		if (200 == code && fails.length <= 0) {
			return true;
		} else {
			StringBuilder sb = new StringBuilder();
			for(int i = 0;i<fails.length;i++)
				sb.append(" "+fails[i].toString());
			logger.info("fails:{}",sb.toString());
		}
		return false;
	}

//	public static void main(String[] args) {
//		//logger.info("send:{}",send("连旅|UNLOCK|0331150822|", "1064868372389"));
//		logger.info("send:{}",send("连旅|UNLOCK|0331150822|", "1064868951488"));
//	}
}
